package com.base.util

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import com.base.R

class NotifyHelper(
    private val _context: Context,
    private val _channelId: String,
    private val _channelName: String,
    private val _channelDesc: String = ""
) {
    private var notificationManager: NotificationManager? = null
    private lateinit var builder: NotificationCompat.Builder

    init {
        notificationManager =
            _context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager?
        createNotificationChannel()
    }

    private fun createNotificationChannel() {
        builder = getNotification(_context, _channelId)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                _channelId, _channelName,
                NotificationManager.IMPORTANCE_DEFAULT
            )
            channel.description = _channelDesc
            builder.setChannelId(_channelId)

            notificationManager?.createNotificationChannel(channel)
        }
    }

    /**
     * @param serviceType ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
     */
    fun startForeground(
        service: Service, notifyId: Int, serviceType: Int = 1
    ) {
        ServiceCompat.startForeground(service, notifyId, builder.build(), serviceType)
    }

    fun getNotificationBuilder(): NotificationCompat.Builder {
        return builder
    }

    /**
     * 更新通知
     *
     * */
    fun notify(notifyId: Int, notification: Notification) {
        notificationManager?.notify(notifyId, notification)
    }

    companion object {

        @JvmStatic
        fun getNotification(
            context: Context, channelId: String,
            iconId: Int = R.mipmap.ic_launcher,
            title: CharSequence = "",
            text: CharSequence = ""
        ): NotificationCompat.Builder {
            val builder = NotificationCompat.Builder(context, channelId)
            builder.setSmallIcon(iconId)
                .setContentTitle(title)
                .setContentText(text)
                .setPriority(NotificationCompat.PRIORITY_LOW)

            return builder
        }

        /**
         * STOP_FOREGROUND_REMOVE 是用于控制前台服务通知行为的标志参数，主要作用如下：
         * ‌基本功能‌
         *      该标志用于Service.stopForeground()方法，决定是否同时移除与前台服务关联的状态栏通知。当设置为STOP_FOREGROUND_REMOVE时，停止前台服务会同步移除通知；若使用STOP_FOREGROUND_DETACH则仅将服务转为后台状态而保留通知显示
         * ‌使用场景‌
         *      需要完全终止服务并清理通知时使用STOP_FOREGROUND_REMOVE
         *      若需保持通知可见（如音乐播放器的暂停状态），则选择STOP_FOREGROUND_DETACH
         * ‌版本适配‌
         *      从Android 8.0（API 26）开始，系统强制前台服务必须显示通知，且默认情况下用户无法通过滑动移除该通知，必须通过代码显式控制
         * ‌注意事项‌
         *      错误使用可能导致通知残留或服务异常终止，需结合onDestroy()生命周期方法确保资源释放
         * */
        @JvmStatic
        fun stopForeground(service: Service, flag: Int = ServiceCompat.STOP_FOREGROUND_REMOVE) {
            ServiceCompat.stopForeground(service, flag)
        }
    }
}
